package entity

import (
	"bytes"
	"fmt"
	"go-yuque/logger"
	"gopkg.in/yaml.v3"
	"os"
	"strings"
)

var configP *PropertyStruct

func init() {
	allArgs := os.Args[1:]
	env := "prod"
outOfSetEnv:
	for _, arg := range allArgs {
		switch strings.ToLower(arg) {
		case "dev":
			env = "dev"
			logger.Infof("当前环境:%s\n", arg)
			break outOfSetEnv
		case "prod":
			env = "prod"
			logger.Infof("当前环境:%s\n", arg)
			break outOfSetEnv
		}
	}

	propertyFile := fmt.Sprintf("./property_%s.yaml", env)
	if env == "prod" {
		_, err := os.Stat(propertyFile)
		if err != nil {
			propertyFile = "./property.yaml"
			logger.Errorf("prod 配置文件不存在，更改配置文件为:%s", propertyFile)
		}
	}
	logger.Infof("读取配置文件...[%s]", propertyFile)
	// 读取配置文件
	config, err := ReadConfig(propertyFile)
	if err != nil {
		logger.Errorf("error reading config: %v", err)
		config = &PropertyStruct{
			TargetDir: "./output",
		}
	}
	configP = config

	logger.Infof(fmt.Sprintf("读取配置文件结束:%v", *configP))
}

type PropertyStruct struct {
	Server struct {
		Port int64 `name:"服务端口" yaml:"port"`
	} `yaml:"server"`
	TargetDir string `name:"生成的笔记存放目录" yaml:"targetDir"`
	Yuque     struct {
		Cookies string `name:"语雀登陆后的Cookie" yaml:"cookies"`
	} `yaml:"yuque"`
	SessionStore string `yaml:"sessionStore"`
	Redis        struct {
		Host     string `yaml:"host"`
		Port     int64  `yaml:"port"`
		Username string `yaml:"username"`
		Password string `yaml:"password"`
		Db       string `yaml:"db"`
	} `yaml:"redis"`
}

func GetTargetDir() string {
	return (*configP).TargetDir
}

func GetYuqueCookies() string {
	return (*configP).Yuque.Cookies
}

func GetServerPort() int64 {
	return (*configP).Server.Port
}

func GetSessionStore() string {
	return (*configP).SessionStore
}

func GetRedisHost() string {
	return (*configP).Redis.Host
}

func GetRedisPort() int64 {
	return (*configP).Redis.Port
}

func GetRedisDb() string {
	return (*configP).Redis.Db
}

func GetRedisUsername() string {
	return (*configP).Redis.Username
}

func GetRedisPw() string {
	return (*configP).Redis.Password
}

func ReadConfig(configPath string) (*PropertyStruct, error) {
	fileBytes, err := os.ReadFile(configPath)
	if err != nil {
		return nil, err
	}

	reader := bytes.NewReader(fileBytes)
	decoder := yaml.NewDecoder(reader)

	var config PropertyStruct

	err = decoder.Decode(&config)
	if err != nil {
		return nil, err
	}

	return &config, nil
}
